<template>
  <div class="CostSecondTrial">
    <group label-width="1rem" label-align="left" gutter="0">
      <cell>
        <span slot="title">报销人</span>
        <span slot="after-title">{{nickName}}</span>
        <!--<span slot="after-title" style="margin-left: 5px">部门</span>-->
        <span slot="after-title" style="margin-left: 20px">{{departmentName}}</span>
        <span slot="child" class="titleChild">{{_dateFormat(createdTime)}}</span>
      </cell>
      <cell is-link @click.native="gotoWorkOrderDetail()">
        <span slot="title">工单编号</span>
        <span slot="after-title">{{workOrderCode}}</span>
      </cell>
      <cell v-if="requestCode" is-link @click.native="gotoRequestDetail()">
        <span slot="title">申请单号</span>
        <span slot="after-title">{{requestCode}}</span>
      </cell>
      <cell>
        <span slot="title">报销单号</span>
        <span slot="after-title">{{code}}</span>
      </cell>
    </group>
    <div v-if="$route.query.type != 1" :class="itemAnimate" class="flex-table">
      <x-table :cell-bordered="false" :content-bordered="false">
        <thead>
        <tr>
          <th style="width: 20%">费用科目</th>
          <th style="width: 15%">复审</th>
          <th style="width: 15%">初审</th>
          <th style="width: 15%">填报</th>
          <th style="width: 15%">差额</th>
          <th style="width: 10%;border-left: 1px solid #E5E5E5;">税率</th>
          <th style="width: 10%">税额</th>
        </tr>
        </thead>
        <tbody>
        <tr class="colorBlue" v-for="(item,index) in costList" :key="index">
          <td :title="item.subjectName||''" class="overflowHide">{{item.subjectName||""}}</td>
          <td>{{item.secondFigure||0}}</td>
          <td>{{item.showBeforeFigure?item.firstFigure:0}}</td>
          <td>{{item.showBeforeFigure?item.fillFigure:0}}</td>
          <td>{{item.showBeforeFigure?(item.secondFigure - item.firstFigure):0}}</td>
          <td style="border-left: 1px solid #E5E5E5;">{{0}}</td>
          <td>{{0}}</td>
        </tr>
        <tr>
          <td>合计</td>
          <td>{{secondFigure}}</td>
          <td>{{firstFigure}}</td>
          <td>{{fillFigure}}</td>
          <td style="color: #99232a">{{secondFigure - firstFigure}}</td>
          <td style="border-left: 1px solid #E5E5E5;">0</td>
          <td>0</td>
        </tr>
        </tbody>
      </x-table>
    </div>
    <tab active-color="#43A2FE" style="margin-top: 10px" v-model="currentIndex">
      <tab-item v-for="(item, index) in costList" :key="index" :selected="index===currentIndex">
        <span>明细{{index+1}}</span>
      </tab-item>
    </tab>
    <swiper ref="swiper" :threshold="10000" :min-moving-distance="10000" v-model="currentIndex" :show-dots="false" @on-index-change="setHeight">
      <swiper-item v-for="(item, index) in costList" :key="index">
        <CostDetail v-if="index==currentIndex" firstOrSecond="2" ref="swiper_item" :formdata="item"></CostDetail>
      </swiper-item>
    </swiper>
    <group v-if="$route.query.type == 1&&$route.query.auth == 1" label-width="1rem" gutter="10px" label-align="left">
      <cell class="fixedLength">
        <span slot="title">初审意见</span>
        <span slot="child">{{firstOption}}</span>
      </cell>
      <cell class="fixedLength">
        <span slot="title">复审意见</span>
        <span slot="child">{{secondOption}}</span>
      </cell>
    </group>
    <template v-if="$route.query.type != 1">
      <group label-width="1rem" gutter="10px" label-align="left"
             style="margin-bottom: 10px">
        <x-textarea title="审批意见" v-model="secondOption" :max="140" placeholder="请输入">
        </x-textarea>
      </group>
      <x-button type="primary" @click.native="approval(true)">通过</x-button>
    </template>
  </div>
</template>

<script>
  import {
    Group,
    Cell,
    CellBox,
    XInput,
    XTable,
    Flexbox,
    FlexboxItem,
    Tab,
    TabItem,
    Swiper,
    SwiperItem,
    Selector,
    XButton,
    XTextarea,
    TransferDom,
    XDialog,
    Previewer,
  } from 'vux'
  import CostDetail from './costDetail.vue'

  export default {
    name: "CostSecondTrial",
    components: {
      Group,
      Cell,
      CellBox,
      XInput,
      XTable,
      Flexbox,
      FlexboxItem,
      Tab,
      TabItem,
      Swiper,
      SwiperItem,
      CostDetail,
      Selector,
      XButton,
      XTextarea,
      XDialog,
      Previewer,
    },
    directives: {
      TransferDom
    },
    data() {
      return {
        nickName: '',//报销人
        departmentName: '',//部门
        createdTime: '',//创建时间
        workOrderCode: '',//工单编号
        code: '',//报销单号
        requestCode: '',//申请单号
        costList: [],//费用列表
        currentIndex: 0,//当前费用明细
        secondOption: '',//复审审批意见
        firstOption: '',//初审意见
        itemAnimate: "",
      }
    },
    mounted() {
      if (this.$route.query.id) {
        this.$http.get('/expense/api/expenseForm/' + this.$route.query.id).then(res => {
            // 格式化后端数据至前端
            let object = res.data.data;
            this.id = object.id;
            this.workOrderCode = object.workOrderCode;
            this.code = object.code;
            this.firstOption = object.firstOption;
            this.secondOption = object.secondOption;
            //判断工单对应的申请单
            this.$http.get('/expense/api/RequestForm', {
              params: {
                workOrderCode: object.workOrderCode,
                noPage: true,
              }
            }).then(resp => {
                if (resp.data.data.length > 0) {
                  this.requestCode = resp.data.data[0].code;
                  this.requestId = resp.data.data[0].id;
                }
              }
            );
            this.createdTime = object.createdTime;
            this.nickName = object.expenseUser && object.expenseUser.nickName;
            this.departmentName = object.expenseUser && object.expenseUser.department && object.expenseUser.department.departmentName;
            let promisesAll = [];
            object.expenseFormItems.forEach(item => {
              promisesAll.push(new Promise((resolveAll, rejectAll) => {
                item.subjectList = JSON.parse(item.subjectContent);
                item.secondFigure = item.secondFigure || '';
                item.showBeforeFigure = false;//控制之前对比金额的显示
                //如果没图片就不发请求了
                if(!item.invoiceFileStore&&!item.voucherFileStore){
                  item.allImgs = [];
                  resolveAll();
                //如果有两类图片 发送两类请求
                }else if(item.invoiceFileStore&&item.voucherFileStore){
                  this.$http.all([
                    this.$http.get('/work/api/upload/byid', {params: {ids: item.invoiceFileStore}}),
                    this.$http.get('/work/api/upload/byid', {params: {ids: item.voucherFileStore}})
                  ]).then(this.$http.spread((res1, res2) => {
                    item.allImgs = res1.data.data[item.invoiceFileStore].concat(res2.data.data[item.voucherFileStore]).map(r => {
                      return {msrc: this._getPathNo(r.path), src: this._getPathNo(r.path)}
                    });
                    resolveAll();
                  }));
                //否则有那个请求就发那个请求
                }else{
                  this.$http.get('/work/api/upload/byid', {params: {ids: item.invoiceFileStore||item.voucherFileStore}}).then(res=>{
                    item.allImgs = res.data.data[item.invoiceFileStore||item.voucherFileStore].map(r => {
                      return {msrc:this._getPathNo(r.path), src:this._getPathNo(r.path)}
                    });
                    resolveAll();
                  })
                }
              }));
            });
            Promise.all(promisesAll).then(() => {
              this.costList = object.expenseFormItems;
              this.$nextTick(() => {
                switch (this.costList.length) {
                  case 0:
                  case 1:
                    this.itemAnimate = 'itemAnimate90';
                    break;
                  case 2:
                    this.itemAnimate = 'itemAnimate120';
                    break;
                  default:
                    this.itemAnimate = 'itemAnimate150';
                    break;
                }
              });
              //确定科目类别之再确定高度
              this.setHeight();
            })
          }
        )
      }
      else {
        this.setHeight()
      }
    },
    computed: {
      firstFigure() {
        return this.costList.reduce((total, item) => {
          let sum = total
          if (item.showBeforeFigure) {
            sum += parseInt(item.firstFigure || 0)
          }
          return sum
        }, 0);
      }
      ,
      fillFigure() {
        return this.costList.reduce((total, item) => {
          let sum = total;
          if (item.showBeforeFigure) {
            sum += parseInt(item.fillFigure || 0)
          }
          return sum
        }, 0);
      },
      secondFigure() {
        return this.costList.reduce((total, item) => {
          let sum = total
          if (item.status === 1 && item.showBeforeFigure) {
            sum += parseInt(item.secondFigure || 0)
          }
          return sum
        }, 0);
      }
    },
    methods: {
      // 申请单界面
      gotoRequestDetail() {
        this.$router.push({path: '/expense/CostApplyTrial', query: {id: this.requestId, type: 1,auth:1}})
      },
      // 工单界面
      gotoWorkOrderDetail() {
        let params = {code: this.workOrderCode}
        this.$http.get('/work/api/workorder', {params: params}).then(res => {
            if (res.data.data.rows.length > 0)
              this.$router.push({path: '/engineer/enWorkingOrder', query: {orderId: res.data.data.rows[0].id}})
          }
        )
      },
      //提交数据
      approval(index) {
        let expenseFormItems = this.costList.map(item => {
          return {id: item.id, status: item.status, secondFigure: parseInt(item.secondFigure)}
        });
        let params = {
          expenseFormItems: expenseFormItems,
          secondAudit: {id: this.$store.state.user.userInfo.id},
          secondOption: this.secondOption,
          secondTrialAmount: this.secondFigure,
        };
        this.$vux.confirm.show({
          title: '提醒',
          content: '请检查数据是否填写完整，审批后无法撤回，是否确定提交？',
          onCancel: () => {

          },
          onConfirm: () => {
            this.$http.put('/expense/api/expenseForm/' + this.id + '/second?audit=' + index, params).then(res => {
              let content = '操作完成，请悉知！'
              if (res.data.data.status == 3) {
                content = '复审完成，请悉知！'
              }
              if (res.data.data.status == 4) {
                content = '驳回完成，请悉知！'
              }
              this.$vux.alert.show({
                title: '复审结果',
                content: content,
                onShow() {
                },
                onHide: () => {
                  this.$router.go(-1)
                }
              })
            });
          }
        })

      },
      //图片预览
      show(index) {
        this.$refs.previewer.show(index)
      },
      showBig() {
        this.showBigPicture = !this.showBigPicture;
      },
      //设置swapper高度
      setHeight() {
        this.$nextTick(() => {
          this.$refs.swiper.xheight = this.$refs.swiper_item[0].$el.clientHeight + 'px'
        })
      },
    }
  }
</script>

<style lang="less">
  .CostSecondTrial {
    .fixedLength{
      .vux-cell-primary{
        flex: 0 0 auto;
      }
    }
    .weui-label {
      text-align-last: justify;
      padding-right: .2rem;
    }
    .vux-label {
      text-align-last: justify;
      padding-right: .2rem;
    }
    .weui-cells{
      line-height: 1.3em;
    }
    .weui-cell {
      line-height: 1.5em;
      padding: 5px 10px;
    }
    .weui-input{
      line-height: 1.5em;
      height: 1.5em;
    }
    .titleChild {
      font-size: 13px;
      position: relative;
      bottom: -5px;
    }
    .colorBlue {
      color: #43A2FE;
    }
    .flex-table {
      overflow: auto;
      background: #fff;
      > table {
        table-layout: fixed;
      }
      .overflowHide {
        word-break: keep-all;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
    .itemAnimate90 {
      animation: move90 1.5s forwards;
    }
    @keyframes move90 {
      100% {
        height: 90px;
      }
    }
    .itemAnimate120 {
      animation: move120 1.5s forwards;
    }
    @keyframes move120 {
      100% {
        height: 120px;
      }
    }
    .itemAnimate150 {
      animation: move150 1.5s forwards;
    }
    @keyframes move150 {
      100% {
        height: 150px;
      }
    }
    .imgBox {
      width: 80px;
      height: 100%;
      padding: 10px 5px;
      text-align: center;
      > img {
        width: 70px;
      }
    }
    .vux-table {
      line-height: 30px;
      font-size: 13px;
    }
    .vux-x-textarea {
      .weui-cell__bd {
        padding: 2px;
        border: 0.01rem solid #E5E5E5;
        border-radius: 5px;
      }
    }
    .weui-cell_select .weui-cell__bd:after {
      border-color: #3FBCFC;
      right: 22px;
      border-width: 0 2px 2px 0;
    }
    .weui-btn {
      background: #43A2FE;
      border-radius: 0;
    }
  }
</style>
